import { hash } from 'ohash'
import { ElMessage } from "element-plus";

// 后端返回的数据类型
export interface ResOptions<T> {
   data?: T
   status?: number
   message?: string
}

/**
 * api请求封装
 * @param { String } url 请求地址
 * @param { Object } options useFtech第二个参数
 */

const cnyzsRequest = (url: string, options?: any) => {

   const key = hash(JSON.stringify(options) + url)
   const TOKEN = useCookie("CNYZSTOKEN").value || ""
   const headers = {
      TOKEN: TOKEN,
      ...options.headers,
   } // 设置默认请求头

   const body = JSON.stringify(options.data)
   return new Promise(async (resolve, reject) => {
      const { data, error } = await useFetch(url,
         { key: key, method: options.method, headers, body: body })
      if (error.value) return console.log(error.value), reject(error.value)
      const value = data.value as ResOptions<any>
      if (!value) {
         console.log('后端接口报错', data.value);
         throw createError({
            statusCode: 500,
            statusMessage: url,
            message: '接口未知错误',
         })
      } else {
         if (value.status === 500) {
            console.log("服务端错误", data.value);
            if (process.client) {
               ElMessage.error(value.message)
               resolve(data.value)
            }
         }
         else {
            if (value.status === 40001) {
               // 无权限
               reject(value.message)
            }
            else {
               // 正常返回
               resolve(data.value)
            }
         }
      }
   })
}

export default cnyzsRequest
